package com.zzyl.nursing.controller.member;

import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.zzyl.common.core.controller.BaseController;
import com.zzyl.common.core.domain.AjaxResult;
import com.zzyl.common.core.domain.R;
import com.zzyl.common.exception.base.BaseException;
import com.zzyl.common.utils.UserThreadLocal;
import com.zzyl.nursing.domain.Device;
import com.zzyl.nursing.domain.Elder;
import com.zzyl.nursing.domain.ElderFamily;
import com.zzyl.nursing.domain.Room;
import com.zzyl.nursing.dto.UserLoginRequestDto;
import com.zzyl.nursing.service.*;
import com.zzyl.nursing.vo.*;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.*;
import java.util.function.Function;
import java.util.stream.Collectors;

/**
 * 老人家属Controller
 *
 * @author JQ
 * @date 2025-08-01
 */
@Tag(name = "老人家属")
@RestController
@RequestMapping("/member/user")
public class FamilyMemberController extends BaseController {
    private static final Logger log = LoggerFactory.getLogger(FamilyMemberController.class);
    @Autowired
    private IFamilyMemberService familyMemberService;

    @Autowired
    private IElderService elderService;

    @Autowired
    private IElderFamilyService elderFamilyService;

    @Autowired
    private IRoomService roomService;

    @Autowired
    private IDeviceService deviceService;

    @Autowired
    private IDeviceDataService deviceDataService;

    @PostMapping("/login")
    @Operation(description = "小程序登录")
    public AjaxResult login(@RequestBody UserLoginRequestDto userLoginRequestDto) {
        LoginVo loginVo = familyMemberService.login(userLoginRequestDto);
        return success(loginVo);
    }

    /**
     * 绑定家人
     *
     * @param elderFamily
     * @return
     */
    @Operation(summary = "绑定家人")
    @PostMapping("/add")
    public R add(@RequestBody ElderFamily elderFamily) {
        Elder elder = elderService.getOne(Wrappers.<Elder>lambdaQuery()
                .eq(Elder::getIdCardNo, elderFamily.getIdCard())
                .eq(Elder::getName, elderFamily.getName())
        );
        if (ObjectUtil.isEmpty(elder)) {
            throw new BaseException("该老人不存在");
        }
        elderFamily.setElderId(elder.getId().intValue());
        Long userId = UserThreadLocal.get();
        elderFamily.setFamilyMemberId(userId.intValue());
        elderFamilyService.save(elderFamily);
        return R.ok();
    }

    /**
     * 获取当前登录用户绑定的老人家属信息
     *
     * @param pageNum  当前页码
     * @param pageSize 每页大小
     * @return 分页查询结果
     */
    @Operation(summary = "获取绑定的老人家属信息")
    @GetMapping("/my")
    public AjaxResult list(Integer pageNum, Integer pageSize) {
        Long userId = UserThreadLocal.get();
        // 设置默认值，防止pageNum或pageSize为null
        if (pageNum == null) {
            pageNum = 1;
        }
        if (pageSize == null) {
            pageSize = 10;
        }
        IPage<ElderFamily> page = new Page<>(pageNum, pageSize);
        List<ElderFamily> list = elderFamilyService.list(page, Wrappers.<ElderFamily>lambdaQuery()
                .eq(ElderFamily::getFamilyMemberId, userId));

        // 转换为 ElderFamilyVo 列表
        List<ElderFamilyVo> voList = new ArrayList<>();
        if (!CollectionUtils.isEmpty(list) && list != null) {
            // 获取所有相关的老人信息
            Set<Integer> elderIds = list.stream()
                    .map(ElderFamily::getElderId)
                    .filter(Objects::nonNull)
                    .collect(Collectors.toSet());

            List<Elder> elders = new ArrayList<>();
            if (!elderIds.isEmpty()) {
                // 批量查询 老人信息
                elders = elderService.listByIds(elderIds.stream()
                        .map(Long::valueOf)
                        .collect(Collectors.toList()));
            }

            Map<Long, Elder> elderMap = elders.stream()
                    .collect(Collectors.toMap(Elder::getId, Function.identity()));

            for (ElderFamily family : list) {
                ElderFamilyVo vo = new ElderFamilyVo();
                vo.setId(family.getId());
                vo.setFamilyMemberId(family.getFamilyMemberId());
                vo.setElderId(family.getElderId());

                Elder elder = elderMap.get(Long.valueOf(family.getElderId()));
                if (elder != null) {
                    vo.setElderName(elder.getName());
                }

                voList.add(vo);
            }
        }

        return AjaxResult.success(voList);
    }

    /**
     * 分页查询当前登录用户的家属信息
     *
     * @return
     */
    @Operation(summary = "分页查询家属信息")
    @GetMapping("/list-by-page")
    public AjaxResult pageList(Integer pageNum, Integer pageSize) {
        // 家属id(登录小程序的人)
        Integer userId = UserThreadLocal.get().intValue();
        // 得到该登陆人的全部家属
        List<ElderFamily> elderFamilyList = elderFamilyService.list(Wrappers.<ElderFamily>lambdaQuery()
                .eq(ElderFamily::getFamilyMemberId, userId));

        IPage<Elder> page = new Page<>(pageNum, pageSize);
        List<ElderFamilyPageVo> list = new ArrayList<ElderFamilyPageVo>();
        // 遍历家属
        elderFamilyList.forEach(ef -> {
            try {
                // 得到家属信息
                Elder elder = elderService.selectElderById(ef.getElderId().longValue());
                if (elder == null) {
                    // 如果老人信息不存在，跳过该记录
                    return;
                }
                // 床位编号
                String bedNumber = elder.getBedNumber();
                // 对床位编号进行分割得到code
                String code = bedNumber.split("-", 2)[0];
                // 根据code得到床位信息然后得到该床位类型
                Room room = roomService.getOne(Wrappers.<Room>lambdaQuery()
                        .eq(Room::getCode, code));
                if (room == null) {
                    // 如果房间信息不存在，跳过该记录
                    return;
                }
                String typeName = room.getTypeName();
                // 根据绑定位置得到设备信息
                Device device = deviceService.getOne(Wrappers.<Device>lambdaQuery()
                        .eq(Device::getBindingLocation, elder.getId()));
                if (device == null) {
                    // 如果设备信息不存在，跳过该记录
                    return;
                }
                String iotId = device.getIotId();
                String deviceName = device.getDeviceName();
                String productKey = device.getProductKey();
                // 对返回结果进行封装
                ElderFamilyPageVo elderFamilyPage = ElderFamilyPageVo.builder()
                        .mid(userId.toString())
                        .mremark(ef.getRemark())
                        .elderId(elder.getId().toString())
                        .name(elder.getName())
                        .image(elder.getImage())
                        .bedNumber(bedNumber)
                        .typeName(typeName)
                        .iotId(iotId)
                        .deviceName(deviceName)
                        .productKey(productKey)
                        .build();
                list.add(elderFamilyPage);
            } catch (Exception e) {
                // 记录异常但不中断整个流程
                log.error("获取家属信息时发生异常，elderId: {}", ef.getElderId(), e);
            }
        });

        return AjaxResult.success(list);
    }

    /**
     * 查询设备健康数据
     * @param iotId 设备id
     * @return
     */
    @Operation(summary = "查询设备健康数据")
    @GetMapping("/queryServiceProperties/{iotId}")
    public R queryDevicePropertyStatus(@PathVariable String iotId){
        List<DeviceShadowVo> deviceShadowVos = deviceService.queryServiceProperties(iotId);
        return R.ok(deviceShadowVos);
    }


    /**
     * 解绑老人
     * @param id 前端传入的实际上是 familyMemberId
     * @return
     */
    @Operation(summary = "解绑老人")
    @DeleteMapping("/deleteById")
    public R deleteById(Long id){
        // 先删除关联的老人家属关系
        elderFamilyService.remove(Wrappers.<ElderFamily>lambdaQuery()
                .eq(ElderFamily::getFamilyMemberId, id));

        // 再删除家属信息
        boolean flag = familyMemberService.removeById(id);
        return R.ok(flag);
    }

    /**
     * 根据设备id按周查询设备数据列表
     * @param iotId 设备id
     * @param functionId 功能id
     * @param endTime 结束时间
     * @param startTime 开始时间
     * @return
     */
    @Operation(summary = "按周查询设备数据列表")
    @GetMapping("/queryDeviceDataListByWeek")
    public R queryDeviceDataListByWeek(String iotId, String functionId, Long endTime, Long startTime){
        List<DataVo> dataVos = deviceDataService.queryDeviceDataListByWeek(iotId, functionId, endTime, startTime);
        return R.ok(dataVos);
    }

    /**
     * 根据设备id按天查询设备数据列表
     * @param iotId 设备id
     * @param functionId 功能id
     * @param endTime 结束时间
     * @param startTime 开始时间
     * @return
     */
    @Operation(summary = "按天查询设备数据列表")
    @GetMapping("/queryDeviceDataListByDay")
    public R queryDeviceDataListByDay(String iotId, String functionId, Long endTime, Long startTime){
        List<DataVo> dataVos = deviceDataService.queryDeviceDataListByDay(iotId, functionId, endTime, startTime);
        return R.ok(dataVos);
    }

}
